<template>
  <div>
    <el-card>
      <el-page-header icon="" title="课程管理">
        <template #content>
          <span class="text-large font-600 mr-3">课程列表</span>
        </template>
      </el-page-header>

      <el-from>
        <el-row :gutter="30" style="margin-top: 20px">
          <el-col :span="7">
            <el-form-item label="学期" prop="term">
              <el-select v-model="query.term" class="m-2" placeholder="Select" style="width: 100%" filterable clearable>
                <el-option v-for="item in termOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="课程名称" prop="coursename">
              <el-input v-model="query.coursename" clearable />
            </el-form-item>
          </el-col>
          <el-button type="primary" @click="handleSerch()">搜索</el-button>
        </el-row>
      </el-from>

      <el-alert title="成绩系数的值为 '平时成绩,实验成绩,期中成绩,期末成绩'" type="warning" :closable="false" show-icon />
      <el-table :data="tableData" style="width: 100%" stripe v-loading="loading">
        <el-table-column prop="courseid" label="课程编号" />
        <el-table-column prop="coursename" label="课程名称" />
        <el-table-column prop="name" label="任课教师" />
        <el-table-column prop="major" label="专业" />
        <el-table-column prop="classes" label="班级" />
        <el-table-column label="学期">
          <template #default="scope">
            {{ scope.row.term === 20231 ? '2023-2024学年第1学期' : '2023-2024学年第2学期' }}
          </template>
        </el-table-column>
        <el-table-column prop="credit" label="学分" />
        <el-table-column prop="type" label="成绩类型">
          <template #default="scope">
            {{ scope.row.type === 1 ? '百分制' : '等级划分制' }}
          </template>
        </el-table-column>
        <el-table-column prop="ratio" label="成绩系数" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="default" @click="handleEdit(scope.row)" :icon="Edit" circle></el-button>
            <el-popconfirm title="你确定要删除吗？" confirm-button-text="确定" cancel-button-text="取消" width="200" @confirm="handleDelete(scope.row)">
              <template #reference>
                <el-button size="default" type="danger" :icon="Delete" circle></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination v-model:current-page="query.page" v-model:page-size="query.limit" :page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="totalCourse" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>
  </div>
</template>

<script setup>
import { Delete, Edit } from '@element-plus/icons-vue'
import { ref, onMounted, reactive, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import axios from 'axios'
const router = useRouter()
const store = useStore()
const loading = ref(true)
const tableData = ref([])
let totalCourse = 0
const query = reactive({
  page: 1,
  limit: 5,
  term: null,
  coursename: ''
})

const termOptions = [
  { label: '2023-2024学年第1学期', value: 20231 },
  { label: '2023-2024学年第2学期', value: 20232 }
]

onMounted(() => {
  getTableData()
})
const getTableData = async () => {
  if (store.state.userInfo.role === 1) {
    // 管理员显示所有课程
    const res1 = await axios.get('/api/course/list', {
      params: query
    })
    const res2 = await axios.get('/api/user/getteacherlist')
    // 将教师工号改为名字
    res1.data.data.forEach((item) => {
      res2.data.data.forEach((i) => {
        if (item['courseteacher'] === i['username']) {
          item['name'] = i['name']
        }
      })
    })
    tableData.value = res1.data.data
    // 获取总条数
    const res = await axios.get('/api/course/total', {
      params: {
        term: query.term,
        coursename: query.coursename
      }
    })
    totalCourse = res.data.data
  } else if (store.state.userInfo.role === 2) {
    // 教师显示自己的课程
    const res1 = await axios.get(`/api/course/mylist/${store.state.userInfo.username}`, {
      params: query
    })
    const res2 = await axios.get('/api/user/getteacherlist')
    // 将教师工号改为名字
    res1.data.data.forEach((item) => {
      res2.data.data.forEach((i) => {
        if (item['courseteacher'] === i['username']) {
          item['name'] = i['name']
        }
      })
    })
    tableData.value = res1.data.data
    // 获取总条数
    const res = await axios.get(`/api/course/mytotal/${store.state.userInfo.username}`, {
      params: {
        term: query.term,
        coursename: query.coursename
      }
    })
    totalCourse = res.data.data
  }
  loading.value = false
}
const handleDelete = async (data) => {
  await axios.delete(`/api/course/list/${data.courseid}`)
  // 更新教师任课信息
  const res = await axios.get(`/api/teacher/getcourse/${data.courseteacher}`)
  let arr = res.data.data[0].mycourses.split(',')
  arr.forEach((item, index) => {
    if (Number(item) === data.courseid) {
      arr.splice(index, 1)
    }
  })
  const newMycourses = arr.join(',')
  await axios.post(`/api/teacher/postcourse/${data.courseteacher}`, { mycourses: newMycourses })

  // console.log(data)
  getTableData()
  ElMessage.success('删除成功！')
}
const handleEdit = (item) => {
  // 跳转到 /course-manage/editcourse/:id
  router.push(`/course-manage/editcourse/${item._id}`)
}

const handleSizeChange = (val) => {
  query.limit = val
  getTableData()
}
const handleCurrentChange = (val) => {
  getTableData()
}
const handleSerch = () => {
  getTableData()
  // 解决pagination视图不更新...
  nextTick(async () => {
    if (store.state.userInfo.role === 1) {
      const res = await axios.get('/api/course/total', {
        params: {
          term: query.term,
          coursename: query.coursename
        }
      })
      totalCourse = res.data.data
    } else {
      const res = await axios.get(`/api/course/mytotal/${store.state.userInfo.username}`, {
        params: {
          term: query.term,
          coursename: query.coursename
        }
      })
      totalCourse = res.data.data
    }
  })
}
</script>

<style lang="scss" scoped>
.el-alert {
  margin-top: 10px;
}
.el-pagination {
  margin-top: 30px;
}
</style>
